<template>
  <div class="app-container" style="padding: 0 !important;">
    <el-form inline size="small" ref="queryForm" :model="queryParams" v-show="showSearch" label-width="100px">

      <el-form-item>
        <el-radio-group v-model="queryParams.allModel" @change="handleQuery">
          <el-radio-button label="false">预定车型</el-radio-button>
          <el-radio-button label="true">全部车型</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="车牌号" prop="carNo">
        <el-input style="width:215px;" v-model="queryParams.carNo"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button v-if="orderNo" icon="el-icon-plus"  size="mini"  @click="addSecondedCar">添加同行车辆</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="list" border>

      <el-table-column label="操作" width="160" align="center">
        <template slot-scope="{row}" v-if="row.status>0&&row.status<5">
          <el-button type="text" @click="handlepeiche(row)" v-if="orderNo" v-hasPermi="['order:orderBasic:supplyCar']">{{row.status<3?'确定配车':'强制配车'}}</el-button>
          <el-button type="text" @click="handlepeicheNoOrder(row)" v-else v-hasPermi="['order:orderBasic:supplyCar']">{{row.status<3?'确定配车':'强制配车'}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="车辆信息" prop="carNo" width="240"  align="center">
        <template slot-scope="scope">
          <div><b>{{scope.row.carNo}}</b></div>
          <div> {{ scope.row.carInfo }}</div>


        </template>
      </el-table-column>
      <el-table-column label="门店信息" prop="carNo" width="160"  align="center">
        <template slot-scope="scope">
          <div>归属:&nbsp;&nbsp;{{scope.row.belongingStore}}</div>
          <div>停靠:&nbsp;&nbsp;{{scope.row.locatedStore}}</div>
        </template>
      </el-table-column>
      <el-table-column label="车辆状态" prop="carNo"  align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.status===0">
            <div> <el-tag type="success">当前排车</el-tag></div>
            <template v-if="scope.row.isSecondmentIn">
              <div>调入时间:&nbsp;&nbsp;{{scope.row.startTime | filterNull}}</div>
              <div>间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr | filterNull}}</div>
            </template>
            <div v-else >间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr | filterNull}}</div>
          </template>
          <template v-if="scope.row.status===1">
            <div><el-tag type="danger">预排推荐车辆</el-tag></div>
            <template v-if="scope.row.isSecondmentIn">
              <div>调入时间:&nbsp;&nbsp;{{scope.row.startTime | filterNull}}</div>
              <div>间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr | filterNull}}</div>
            </template>
            <div v-else >间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr | filterNull}}</div>
          </template>
          <template v-if="scope.row.status===2">
            <div>可排</div>
            <template v-if="scope.row.isSecondmentIn">
              <div>调入时间:&nbsp;&nbsp;{{scope.row.startTime | filterNull}}</div>
              <div>间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr | filterNull}}</div>
            </template>
            <div v-else >间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr | filterNull}}</div>
          </template>
          <template v-if="scope.row.status===3">
            <div>已预排至其他订单【{{scope.row.orderSourceName}}:{{scope.row.orderNo}}】</div>
            <div>若分配此车辆，则预排订单重新排车</div>
            <div>订单时间：{{scope.row.startTime | filterNull}}~{{scope.row.endTime | filterNull}}</div>
            <div>间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr}}</div>
          </template>
          <template v-if="scope.row.status===4">
            <div>已分配至其他订单【{{scope.row.orderSourceName}}:{{scope.row.orderNo}}】</div>
            <div>若强制配车，则下述订单将重新排车</div>
            <div>订单时间：{{scope.row.startTime | filterNull}}~{{scope.row.endTime | filterNull}}</div>
            <div>间隔时间:&nbsp;&nbsp;{{scope.row.intervalTimeStr}}</div>
          </template>
          <template v-if="scope.row.status===5">
            <div>车辆下线<span v-if="scope.row.remark">({{scope.row.remark}})</span></div>
            <div>下架时间：{{scope.row.startTime | filterNull}}~{{scope.row.endTime | filterNull}}</div>
          </template>
          <template v-if="scope.row.status===6">
            <div>车辆借出</div>
            <div>借调时间：{{scope.row.startTime | filterNull}}~{{scope.row.endTime | filterNull}}</div>
          </template>
          <template v-if="scope.row.status===7">
            <div>车辆调拨</div>
            <template v-if="scope.row.endTime">
              <div>调出时间：{{scope.row.startTime | filterNull}}~{{scope.row.endTime | filterNull}}</div>
            </template>
            <template v-else>
              <div>调出时间：{{scope.row.startTime | filterNull}}</div>
            </template>
          </template>
          <template v-if="scope.row.status===8">
            <div>用车中【{{scope.row.orderSourceName}}:{{scope.row.orderNo}}】</div>
            <div>车辆已被其他订单占用，请选择其他车辆</div>
            <div>订单时间：{{scope.row.startTime | filterNull}}~{{scope.row.endTime | filterNull}}</div>
          </template>
        </template>
      </el-table-column>

    </el-table>

     <pagination v-show="total>0" :total="total" :pageSizes="[5,10,15,20,50]" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改同行借调对话框 -->
    <el-dialog title="借入车辆" :visible.sync="open" append-to-body >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单号" prop="orderNo">{{form.orderNo}} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁时间" prop="time">{{form.time}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="预定车型" prop="modelName">{{form.modelName}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="借调同行"
              prop="sameJobName"
              style="width: 100%"
            >
              <el-select
                v-model="form.carBrandId"
                placeholder="请选择借调同行"
                @change="handleSameUpdate"
                style="width: 100%"
                class="el-input-style"
                filterable
                remote
              >
                <el-option
                  v-for="(item, i) in sameDrawerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="车牌号" prop="carNo">
              <el-input v-model="form.carNo" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="车架号" prop="vinNo">
              <el-input v-model="form.vinNo" placeholder="请输入车架号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借调开始日期" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                style="width: 100%"
                placeholder="开始日期"
                @change="changeStartTime"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借调单价" prop="secondedUnitPrice">
              <el-input v-model="form.secondedUnitPrice" placeholder="请输入借调单价" @keyup.native="form.secondedUnitPrice = oninput(form.secondedUnitPrice,2)"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结算方式" prop="settlementWay">
              <el-radio-group v-model="form.settlementWay" size="medium">
                <el-radio
                  v-for="dict in dict.type.settlement_way"
                  :label="parseInt(dict.value)"
                  :value="parseInt(dict.value)"
                  :key="parseInt(dict.value)"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="车辆初始图片" prop="initialPicture">
              <ImageUpload isArray v-model="form.initialPicture"  :limit="20" :zoom="0.6" :fileSize="20"></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" style="width:100%">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="loadingDrawer">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置托管单价" :visible.sync="dialogTuoguanVisible" append-to-body>
      <el-form>
        <el-row :gutter="10">
         <el-col :span="12">
           <el-form-item label="车型">
             <span>{{currentDispatchCar.carInfo}}</span>
           </el-form-item>
         </el-col>
          <el-col :span="12">
            <el-form-item label="托管单价">
              <div style="display: flex;align-items: center;">
                <el-input style="width: 300px" v-model="escrowUnitPrice" placeholder="请输入单价" @keyup.native="escrowUnitPrice = oninput(escrowUnitPrice, 2)">
                  <el-button slot="append">元/天</el-button>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTuoguanVisible = false">取 消</el-button>
        <el-button type="primary" @click="requestDispatchCar">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import * as api from '@/api/order/index'
import {listJob} from "@/api/seconded/job";
import {addSeconded, updateSeconded} from "@/api/seconded/seconded";
import ImageUpload from "@/components/ImageUpload";
import Template from "@/views/system/template";
import {orderEscrowCarDetail} from "@/api/bills/escrow";

export default {
  dicts: ['car_status', 'mmv_jqType','gps_status','seconded_type','settlement_way'],
  props: {
    orderNo: {
      type: String,
      default: '',
    },
    modelId: {
      type: String,
      default: '',
    },
    storeId: {
      type: String,
      default: '',
    },
    orderStartTime: {
      type: String,
      default: null,
    },
    orderEndTime: {
      type: String,
      default: null,
    },
    isOta: {
      type: Boolean,
      default: false,
    },
    rent:{
      type:Number,
      default:null
    }
  },
  components:{
    Template,
    ImageUpload,
  },
  data() {
    return {

      open: false,
      direction: 'rtl',
      queryParamsSame: {
        pageNum: 1,
        pageSize: 1000,
        name: null,
      },
      loading: false,
      loadingDrawer: false,
      sameDrawerList: [],
      totalSame: 0,

      drawerFlag: false,

      list: [],
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      queryParams: {
        carNo: "",//车牌号
        carModelId: this.modelId,//车型id
        belongingStoreId: "",//归属门店id
        locatedStoreId: "",//停靠门店id
        carStatus: "",//车辆状态
        pageNum: 0,//页码   必选
        pageSize: 5,//每页显示数据 必选
        allModel:false//false预定车型  true全部车型
      },

      // 表单参数
      form: {
        startTime:null,
        estimateEndTime:null,
        settlementWay:1,
        estimateDay:0,
        initialPicture:[]
      },
      // 表单校验
      rules: {
        sameJobName: [
          { required: true, message: '同行名称不能为空', trigger: 'change' },
        ],
        startTime: [
          { required: true, message: '借调开始时间不能为空', trigger: 'blur' },
        ],

        actualEndTime: [
          { required: true, message: '借调结束时间不能为空', trigger: 'blur' },
        ],
        totalRent: [
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2})))$/,
            message: '费用输入有误',
            trigger: 'blur',
          },
        ],
        settlementWay: [
          { required: true, message: '结算方式不能为空', trigger: 'blur' },
        ],
        carNo: [
          { required: true, message: '车牌号不能为空', trigger: 'change' },
        ],
      },
      currentDispatchCar:{},
      escrowUnitPrice:null,
      dialogTuoguanVisible:false
    };
  },
  computed: {
    params() {
      const params = {
        isOta: this.isOta,//车牌号
        carNo: this.queryParams.carNo,//车牌号
        carModelId: this.queryParams.carModelId,//车型id
        belongingStoreId: this.queryParams.belongingStoreId,//归属门店id
        locatedStoreId: this.queryParams.locatedStoreId,//停靠门店id
        carStatus: this.queryParams.carStatus,//车辆状态
        orderStartTime: this.orderStartTime,//订单开始
        orderEndTime: this.orderEndTime,//订单结束
        pageNum: this.queryParams.pageNum,//页码   必选
        pageSize: this.queryParams.pageSize,//每页显示数据 必选
        allModel: this.queryParams.allModel,//false预定车型  true全部车型
      };
      return params;
    }
  },
  mounted() {
    this.getList();
    this.getOrderEscrowCarDetail()
  },
  methods: {
    // 获取交还扯托管车辆费用信息
    getOrderEscrowCarDetail(){
      if(this.orderNo){
        orderEscrowCarDetail(this.orderNo).then(res=>{
          if (res.data.carSource==6) {
            this.escrowUnitPrice = res.data.escrowUnitPrice
          }
        })
      }

    },
    changeStartTime(val) {
      let date = new Date(val).getTime()
      this.startTime = date
      if (this.form.estimateEndTime) {
        if (this.startTime > new Date(this.form.estimateEndTime).getTime()) {
          this.$message.error('结束时间不能小于开始时间')
          this.form.startTime = ''
          this.startTime = null
        } else {
          let iDays = parseInt(
            Math.abs(
              new Date(this.form.estimateEndTime).getTime() - this.startTime
            ) /
            1000 /
            60 /
            60 /
            24
          )
          let y =
            (new Date(this.form.estimateEndTime).getTime() - this.startTime) %
            (1000 * 60 * 60 * 24)
          if (y > 0) {
            iDays = iDays + 1
          }
          this.form.estimateDay = iDays
        }
      }
    },
    changeEndTime(val) {
      let date = new Date(val).getTime()
      this.endTime = date

      if(!this.form.estimateEndTime){
        this.form.estimateEndTime = ''
        this.endTime = null
        this.form.estimateDay = null
        return
      }
      if (this.form.startTime) {
        if (this.endTime < new Date(this.form.startTime).getTime()) {
          this.$message.error('结束时间不能小开始时间')
          this.form.estimateEndTime = ''
          this.endTime = null
        } else {
          let iDays = parseInt(
            Math.abs(this.endTime - new Date(this.form.startTime).getTime()) /
            1000 /
            60 /
            60 /
            24
          )
          let y =
            (this.endTime - new Date(this.form.startTime).getTime()) %
            (1000 * 60 * 60 * 24)
          if (y > 0) {
            iDays = iDays + 1
          }
          this.form.estimateDay = iDays
        }
      } else {
        this.$message.error('请选择开始时间')
        this.form.estimateEndTime = ''
        this.endTime = null
      }
    },
    cancel() {
      this.open = false
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loadingDrawer = true
          addSeconded(this.form).then((response) => {
            const data = {
              orderNo: this.orderNo,
              carId: response.data,
            };
            api.supplyCar(data).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open=false
              this.$emit('close');
            }).finally(err=>{
              this.loadingDrawer =false
            });
          }).catch(err=>{
            this.loadingDrawer =false
          })
        }
      })
    },
    getList() {
      let param = {
        ...this.params,
        orderNo: this.orderNo,
        modelId: this.modelId,
        storeId: this.storeId
      }

      this.loading = true
      api.carListByMaintenancePc(param).then(response => {
        this.list = response.rows;
        this.total=response.total;
        this.loading =false
      });
    },
    // 确定配车
    handlepeiche(row) {
      this.currentDispatchCar = row;
      if(row.carSource == 6) {//托管车辆->弹框设置托管单价
        this.dialogTuoguanVisible = true;
      }else {//自营车辆->直接分配
        this.requestDispatchCar();
      }
    },


    // 请求分配车辆
    requestDispatchCar(){
      let params= {
        isOta : this.isOta,
        orderNo : this.orderNo,
        carId: this.currentDispatchCar.carId,
        carSource:this.currentDispatchCar.carSource,
        escrowUnitPrice:this.escrowUnitPrice,
      }
      api.supplyCar(params).then(response => {
        this.dialogTuoguanVisible = false;
        this.$modal.msgSuccess("操作成功");
        this.$emit('close');
      });
    },

    addSecondedCar(){
      api.detail(this.orderNo).then((res) => {
        let orderInfo=res.data.orderInfo
        this.form.orderNo = orderInfo.orderNo
        this.form.secondedType = 1
        this.form.modelName = orderInfo.modelName
        this.form.startTime = orderInfo.rentalStartTime + ':00'
        this.form.estimateEndTime = orderInfo.rentalEndTime + ':00'
        this.form.time = orderInfo.rentalStartTime + ' 至 ' + orderInfo.rentalEndTime
        this.form.estimateDay = orderInfo.leaseDays
        this.open=true
        this.getSameList()
      })

    },
    resetQuerySame() {
      this.resetForm('querySameForm')
      this.handleQuerySame()
    },
    selectSame() {
      this.resetQuerySame()
      this.drawerFlag = true
    },
    handleQuerySame() {
      this.queryParamsSame.pageNum = 1
      this.getSameList()
    },
    /** 查询借调同行列表 */
    getSameList() {

      listJob(this.queryParamsSame).then((response) => {
        this.sameDrawerList = response.rows
        this.totalSame = response.total
      })
    },
    //选择同行
    handleSameUpdate(id) {
      this.form.sameJobId = id
      this.form.sameJobName =this.sameDrawerList.filter(item=>{
        return item.id==id
      })[0].name
    },
    // 确定配车
    handlepeicheNoOrder(row) {
      const data = {
        orderNo: this.orderNo,
        carId: row.carId,
        carNo: row.carNo,
        isOta: this.isOta,//车牌号
        carSource:row.carSource
      };
      this.$emit('close',data);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
}
</script>
<style>
.sucess-text{
  color: #13ce66;font-size: 12px
}
.warning-text{
  color: #ffba00;font-size: 12px
}
.danger-text{
  color: #ff4949
}
</style>
